package com.jinghangzz.shop.goods.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jinghangzz.shop.common.service.impl.BaseServiceImpl;
import com.jinghangzz.shop.common.util.ConstatFinalUtil;
import com.jinghangzz.shop.common.util.PageInfoUtil;
import com.jinghangzz.shop.goods.dao.IAGoodsBrandDao;
import com.jinghangzz.shop.goods.dao.IAGoodsCateDao;
import com.jinghangzz.shop.goods.dao.IAGoodsDao;
import com.jinghangzz.shop.goods.pojo.AGoods;
import com.jinghangzz.shop.goods.pojo.AGoodsBrand;
import com.jinghangzz.shop.goods.pojo.AGoodsCate;
import com.jinghangzz.shop.goods.service.IGoodsOperService;
import com.jinghangzz.shop.goods.service.IGoodsService;

/**
 * Goods模块的Service实现类
 * @author TeaBig
 */
@Service("goodsService")
public class GoodsServiceImpl extends BaseServiceImpl implements IGoodsService
{
	@Resource
	private IAGoodsBrandDao goodsBrandDao;
	@Resource
	private IAGoodsCateDao goodsCateDao;
	@Resource
	private IAGoodsDao goodsDao;
	
	@Resource
	private IGoodsOperService goodsOperService;
	
	@Override
	public AGoodsBrand findOneGoodsBrandService(Map<String, Object> condMap)
	{
		return this.goodsBrandDao.findOneDao(condMap);
	}

	@Override
	public List<AGoodsBrand> findCondListGoodsBrandService(PageInfoUtil pageInfoUtil,Map<String, Object> condMap)
	{
		/* 让关键字使用模糊匹配 */
		if(condMap.get("keyword") != null && !"".equalsIgnoreCase(condMap.get("keyword") + ""))
		{
			condMap.put("keyword", "%" + condMap.get("keyword") + "%");
		}
		if(pageInfoUtil != null)
		{
			/* 要分页 */
			Page page = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			List<AGoodsBrand> goodsBrandList = this.goodsBrandDao.findCondList(condMap);
			/* 分页两要素:
			 * 共多少条
			 * 每页多少条
			 *  */
			pageInfoUtil.setTotalRecord(Integer.valueOf(page.getTotal() + ""));
			return goodsBrandList ; 
		}
		/* 不分页 */
		return this.goodsBrandDao.findCondList(condMap);
	}

	@Override
	public JSONObject saveOneGoodsBrandService(AGoodsBrand goodsBrand) throws Exception
	{
		JSONObject resultJSON = new JSONObject();
		
		goodsBrand.setCreateTime(new Date());
		goodsBrand.setUpdateTime(new Date());
		int res =  this.goodsBrandDao.saveOne(goodsBrand);
		
		if(res > 0 )
		{
			/* 保存成功 */
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.getString("0"));
			/* 返回值为JSON */
			JSONObject dataResJSON = new JSONObject();
			dataResJSON.put("effect", res);
			dataResJSON.put("id", goodsBrand.getId());
			
			resultJSON.put("data", dataResJSON);
		}else
		{
			/* 保存失败 */
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.getString("-1"));
		}
		
		/* 制作一个异常
		 * 期望如果有异常,保存的记录要回滚(事务回滚)
		 *  */
//		try
//		{
////			String str = null ; 
////			str.toString() ;
//			
//			/* 造一个异常,不是runTimeException */
//			int i = 4 / 0 ; 
//		} catch (Exception e)
//		{
//			throw new Exception("aaaa") ; 
//		} 
		return resultJSON ; 
	}

	@Override
	public JSONObject updateOneGoodsBrandService(AGoodsBrand goodsBrand) throws Exception
	{
		JSONObject resultJSON = new JSONObject();
		goodsBrand.setUpdateTime(new Date());
		int res =  this.goodsBrandDao.updateOne(goodsBrand);
		if(res > 0 )
		{
			/* 保存成功 */
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.getString("0"));
			/* 返回值为JSON */
			JSONObject dataResJSON = new JSONObject();
			dataResJSON.put("effect", res);
			
			resultJSON.put("data", dataResJSON);
		}else
		{
			/* 保存失败 */
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.getString("-1"));
		}
		return resultJSON ; 
	}
	
	@Override
	public JSONObject updateOneGoodsBrandService(AGoodsBrand goodsBrand, Map<String, Object> paramsMap) throws Exception
	{
		/* 先更新数据库 */
		JSONObject resultDbJSON = this.updateOneGoodsBrandService(goodsBrand);
		
		/* 原来的 */
		String souPath = goodsBrand.getLogoPath() ; 
		String originalFilename = paramsMap.get("originalFilename") + ""; 
		InputStream inputStream = (InputStream) paramsMap.get("inputStream");
		/* 路径写到配置文件中 */
		String truePath = ConstatFinalUtil.SYS_CONFIG_JSON.getString("file.truePath") ; 
		String webPath = ConstatFinalUtil.SYS_CONFIG_JSON.getString("file.webPath") ; 
		/* 获取扩展名
		 * 1.png
		 *  */
		String relaPath = ConstatFinalUtil.SYS_CONFIG_JSON.getString("file.realPath") +  "/goods/brand/2019-09-20/" + UUID.randomUUID().toString() 
				+ originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length()); 
		ConstatFinalUtil.SYS_LOGGER.info("truePath:{}",truePath);
		ConstatFinalUtil.SYS_LOGGER.info("webPath:{}",webPath);
		ConstatFinalUtil.SYS_LOGGER.info("relaPath:{}",relaPath);
		/* 绝对路径:硬盘上的绝对路径 */
		File trueFile = new File(truePath + relaPath);
		/* 创建父目录
		 * getParentFile:获取上一级目录的对象;
		 * exists:判断此目录是否存在
		 *  */
		if(!trueFile.getParentFile().exists())
		{
			/* 创建目录:
			 * mkdir:
			 * mkdirs:
			 *  */
			trueFile.getParentFile().mkdirs() ; 
		}
		FileOutputStream fos = new FileOutputStream(trueFile);
		/* 有输入流,有文件,直接拷贝 */
		if(!this.fileUtil.copy(inputStream, fos))
		{
			ConstatFinalUtil.SYS_LOGGER.error("拷贝文件失败了,原文件:{}",trueFile);
		}else
		{
			/* 拷贝成功,要把相对路径存储到数据库 */
			goodsBrand.setLogoPath(relaPath);
			goodsBrand.setUpdateTime(new Date());
			this.updateOneGoodsBrandService(goodsBrand);
			
			/* 删除老图片 */
			File souFile = new File(truePath + souPath);
			boolean deleteFlag = souFile.delete() ; 
			ConstatFinalUtil.SYS_LOGGER.info("品牌删除图片标识:{},原文件:{}",deleteFlag, souFile);
		}
		return resultDbJSON;
	} 

	@Override
	public JSONObject deleteBatchGoodsBrandService(Map<String, Object> condMap) throws Exception
	{
		JSONObject resultJSON = new JSONObject();
		int res = this.goodsBrandDao.deleteBatch(condMap);
		if(res > 0 )
		{
			/* 保存成功 */
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.getString("0"));
			/* 返回值为JSON */
			JSONObject dataResJSON = new JSONObject();
			dataResJSON.put("effect", res);
			
			resultJSON.put("data", dataResJSON);
		}else
		{
			/* 保存失败 */
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.getString("-1"));
		}
		return resultJSON ; 
	}
	
	
	@Override
	public AGoodsCate findOneGoodsCateService(Map<String, Object> condMap)
	{
		return this.goodsCateDao.findOneDao(condMap);
	}
	
	@Override
	public JSONObject saveOneGoodsCateService(AGoodsCate goodsCate)
	{
		JSONObject resultJSON = new JSONObject();
		/* 影响条数 */
		int res = this.goodsCateDao.saveOne(goodsCate);
		/*String str = null ; 
		str.toString();*/
		if(res > 0 )
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			
			/* 存储data */
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("id", goodsCate.getId() + "");
			dataJSON.put("effect", res + "");
			
			resultJSON.put("data", dataJSON);
		}else
		{
			resultJSON.put("code", "1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
		}
		return resultJSON;
	}
	
	@Override
	public JSONObject updateOneGoodsCateService(AGoodsCate goodsCate)
	{
		JSONObject resultJSON = new JSONObject();
		/* 影响条数 */
		int res = this.goodsCateDao.updateOne(goodsCate);
		/*String str = null ; 
		str.toString();*/
		if(res > 0 )
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "成功");
			
			/* 存储data */
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("id", goodsCate.getId() + "");
			dataJSON.put("effect", res + "");
			
			resultJSON.put("data", dataJSON);
		}else
		{
			resultJSON.put("code", "2");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("2"));
		}
		return resultJSON;
	}

	@Override
	public JSONObject deleteOneGoodsCateService(AGoodsCate goodsCate)
	{
		JSONObject resultJSON = new JSONObject();
		return resultJSON;
	}
	
	@Override
	public List<AGoodsCate> findCondListGoodsCateService(PageInfoUtil pageInfoUtil,Map<String, Object> condMap)
	{
		/* 为关键字加上%,实现模糊匹配 
		 * */
		if(condMap.get("keyword") != null && !"".equalsIgnoreCase(condMap.get("keyword") + ""))
		{
			condMap.put("keyword", "%" + condMap.get("keyword")  + "%");
		}
		
		if(pageInfoUtil != null)
		{
			Page page = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			List<AGoodsCate> roleList = this.goodsCateDao.findCondList(condMap);
			pageInfoUtil.setTotalRecord(Integer.valueOf(page.getTotal() + ""));
			return roleList;
		}
		/* 不分页查询数据 */
		List list = this.goodsCateDao.findCondList(condMap);
		return list ; 
	}
	
	@Override
	public AGoods findOneGoodsService(Map<String, Object> condMap)
	{
		return this.goodsDao.findOneDao(condMap);
	}
	
	@Override
	public JSONObject saveOneGoodsService(AGoods goods)
	{
		JSONObject resultJSON = new JSONObject();
		
		goods.setCreateTime(new Date());
		goods.setUpdateTime(new Date());
		
		/* 影响条数 */
		int res = this.goodsDao.saveOne(goods);
		/*String str = null ; 
		str.toString();*/
		if(res > 0 )
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			
			/* 存储data */
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("id", goods.getId() + "");
			dataJSON.put("effect", res + "");
			
			resultJSON.put("data", dataJSON);
		}else
		{
			resultJSON.put("code", "1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
		}
		return resultJSON;
	}
	
	@Override
	public JSONObject updateOneGoodsService(AGoods goods)
	{
		JSONObject resultJSON = new JSONObject();
		goods.setUpdateTime(new Date());
		/* 影响条数 */
		int res = this.goodsDao.updateOne(goods);
		/*String str = null ; 
		str.toString();*/
		if(res > 0 )
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "成功");
			
			/* 存储data */
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("id", goods.getId() + "");
			dataJSON.put("effect", res + "");
			
			resultJSON.put("data", dataJSON);
		}else
		{
			resultJSON.put("code", "2");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("2"));
		}
		return resultJSON;
	}

	@Override
	public JSONObject deleteOneGoodsService(AGoods goods)
	{
		JSONObject resultJSON = new JSONObject();
		return resultJSON;
	}
	
	@Override
	public List<AGoods> findCondListGoodsService(PageInfoUtil pageInfoUtil,Map<String, Object> condMap)
	{
		/**
		 * 先查询一下Redis看看是否有;
		 * 如果有:查询Redis直接返回,
		 * 如果木有:查询数据库,直接返回,并且再放回到Redis中
		 * key:字符串,值:json
		 * goodsList_当前页_搜索条件(keyword_分类id)
		 * goodsList_1_(_)
		 */
		String redisKey = "goodsList_" + pageInfoUtil.getCurrentPage() + "_(" + condMap.get("keyword") + "_" + condMap.get("cateId") + ")" ; 
		/* 从Redis中获取key对应的值 */
		String redisVal = this.redisUtil.get(redisKey);
		if(redisVal == null || "".equalsIgnoreCase(redisVal) || "null".equalsIgnoreCase(redisVal))
		{
			JSONObject resultJSON = new JSONObject();
			/* 从Redis木有找到记录,直接查询数据库 */
			List<AGoods> goodsList = findCondListGoodsDbService(pageInfoUtil, condMap); 
			/* 把数据库中对象的记录放到Redis中 */
			JSONArray goodsArr = new JSONArray();
			for (Iterator iterator = goodsList.iterator(); iterator.hasNext();)
			{
				AGoods goodsTemp = (AGoods) iterator.next();
				/* 放到json中 */
				JSONObject goodsJSON = goodsTemp.toJSON();
				/* 把生成的json放到json数组中 */
				goodsArr.add(goodsJSON);
			}
			resultJSON.put("goodsList", goodsArr);
			/* 有一个小瑕疵
			 * 在把列表放到redis中的时候,请把总条数也放去(因为木有总条数就无法分页)
			 *  */
			resultJSON.put("totalRecord", pageInfoUtil.getTotalRecord());
			/* 把这些放到Redis中 */
			this.redisUtil.set(redisKey, resultJSON.toJSONString(), 60 * 5);
			ConstatFinalUtil.SYS_LOGGER.info("商品列表查询数据库");
			return goodsList ; 
		}else
		{
			ConstatFinalUtil.SYS_LOGGER.info("商品列表查询Redis");
			List<AGoods> goodsList = new ArrayList<AGoods>();
			
			/* 把Redis中的数组变成对象 */
			JSONObject resultJSON = (JSONObject) JSON.parse(redisVal);
			
			JSONArray goodsArr = (JSONArray) resultJSON.get("goodsList");
			for (Iterator iterator = goodsArr.iterator(); iterator.hasNext();)
			{
				JSONObject goodsJSON = (JSONObject) iterator.next();
				/* 要把json字符串变成java对象 */
				AGoods goods = new AGoods();
				goods = goods.parse(goodsJSON.toJSONString(), goods);
				goodsList.add(goods);
			}
			/* 分页 */
			int totalRecord = resultJSON.getIntValue("totalRecord");
			pageInfoUtil.setTotalRecord(totalRecord);
			return goodsList ; 
		}
	}

	/**
	 * 查询数据库
	 * @param pageInfoUtil
	 * @param condMap
	 * @return
	 */
	private List<AGoods> findCondListGoodsDbService(PageInfoUtil pageInfoUtil, Map<String, Object> condMap)
	{
		/* 为关键字加上%,实现模糊匹配 
		 * */
		if(condMap.get("keyword") != null && !"".equalsIgnoreCase(condMap.get("keyword") + ""))
		{
			condMap.put("keyword", "%" + condMap.get("keyword")  + "%");
		}
		
		if(pageInfoUtil != null)
		{
			/*-------------数据库部分----------*/
			/* 分页 */
			/* 查询总记录数 */
			Page page = PageHelper.startPage(pageInfoUtil.getCurrentPage(),pageInfoUtil.getPageSize());
			List<AGoods> goodsList = this.goodsDao.findCondList(condMap);
			
			Map<String,Object> extMap = new HashMap<String, Object>();
			for (Iterator iterator = goodsList.iterator(); iterator.hasNext();)
			{
				AGoods goods = (AGoods) iterator.next();
				
				/* 获取到商品对应的分类 */
				extMap.clear();
				extMap.put("id",goods.getCateId());
				AGoodsCate cate = this.findOneGoodsCateService(extMap);
				
				/* 需要一个祖宗的分类List */
				List<AGoodsCate> arCateList = this.goodsOperService.findListCateTreeService(cate);
				goods.setParentCateList(cate.getAncestorsCateList());
			}
			
			pageInfoUtil.setTotalRecord(Long.valueOf(page.getTotal()).intValue());
			/*-------------数据库部分----------*/
			return goodsList ; 
		}
		/* 不分页查询数据 */
		List<AGoods> goodsList = this.goodsDao.findCondList(condMap);
		return goodsList ;
	}
}
